#  Copyright (c) 2010
#  The Regents of the University of Michigan
#  All Rights Reserved

#  Permission is granted to use, copy, create derivative works, and
#  redistribute this software and such derivative works for any purpose,
#  so long as the name of the University of Michigan is not used in
#  any advertising or publicity pertaining to the use or distribution
#  of this software without specific, written prior authorization. If
#  the above copyright notice or any other identification of the
#  University of Michigan is included in any copy of any portion of
#  this software, then the disclaimer below must also be included.

#  This software is provided as is, without representation or warranty
#  of any kind either express or implied, including without limitation
#  the implied warranties of merchantability, fitness for a particular
#  purpose, or noninfringement.  The Regents of the University of
#  Michigan shall not be liable for any damages, including special,
#  indirect, incidental, or consequential damages, with respect to any
#  claim arising out of or in connection with the use of the software,
#  even if it has been or is hereafter advised of the possibility of
#  such damages.
import datetime
import glob
import psycopg2
import sys

from util import *


def create_god_table(dirs, prefix='peer_lists'):
  subquery = ('''SELECT * FROM %s_''' % prefix) + '%s'
  bigquery = ' UNION '.join(subquery % get_db_suffix(dir) for dir in dirs)
  create_query = 'CREATE TABLE %s_god AS %s' % (prefix, bigquery)

  conn = get_db_conn()
  c = conn.cursor()
  c.execute(create_query)
  conn.commit()
  print '%s: now analyzing' % datetime.datetime.today()
  c.execute('SET maintenance_work_mem=\'4GB\';')
  c.execute('ANALYZE %s_god;' % prefix)

def main():
  dirs = glob.glob(sys.argv[1])
  dirs.sort(key=get_date)
  print 'start at %s' % datetime.datetime.today()
  create_god_table(dirs)
  print 'finish first god table at %s' % datetime.datetime.today()
  create_god_table(dirs, 'torrent_descs')
  print 'finish second god table at %s' % datetime.datetime.today()

if __name__ == '__main__':
  main()
